﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using ZQNB.BaseLib.Core.Models;
using ZQNB.Common;

namespace ZQNB.BaseLib.Core.Services
{
    public class BsSettingService : IBsSettingService
    {
        private readonly CoreDataHelper _fileDbHelper;

        public BsSettingService(CoreDataHelper fileDbHelper)
        {
            _fileDbHelper = fileDbHelper;
        }


        public BsSetting GetBsSetting()
        {
            var setting = _fileDbHelper.Read<BsSetting>().SingleOrDefault();
            if (setting != null)
            {
                var allThemes = GetAllThemes();
                //var currentTheme = setting.Themes.FirstOrDefault(x => x.IsCurrent);
                //if (currentTheme != null)
                //{
                //    BsTheme theTheme = allThemes.FirstOrDefault(x => x.Name.NbEquals(currentTheme.Name));
                //    if (theTheme != null)
                //    {
                //        theTheme.IsCurrent = true;
                //    }
                //}

                setting.Themes = allThemes;
            }
            return setting;
        }

        public void SaveBsSetting(BsSetting model)
        {
            var settings = new List<BsSetting> { model };
            _fileDbHelper.Save(settings);
        }

        private IList<BsTheme> GetAllThemes()
        {
            var excludes = new string[] { "nb" };
            //-nb
            const string themeVirtualPath = "~/Content/libs/bootstrap/css/";
            //read from files
            IList<BsTheme> themes = new List<BsTheme>();
            var themeFolderPath = MyPathHelper.MapIISServerPath(themeVirtualPath);
            List<string> filePaths = MyIOHelper.GetFiles(themeFolderPath, "bootstrap-*.css", SearchOption.TopDirectoryOnly);
            if (filePaths.Count == 0)
            {
                return themes;
            }

            foreach (var filePath in filePaths)
            {
                BsTheme theme = new BsTheme();
                FileInfo fileInfo = new FileInfo(filePath);
                //["bootstrap","cosmo.css"]
                string[] strings = fileInfo.Name.Split('-');
                theme.Name = strings[1].Split('.')[0];
                theme.Path = themeVirtualPath + fileInfo.Name;
                if (excludes.Contains(theme.Name))
                {
                    continue;
                }
                themes.Add(theme);
            }
            return themes;
        }
    }
}